package com.ktg.system.job;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.ktg.system.domain.SysDataSource;
import com.ktg.system.service.ISysDataSourceService;
import com.ktg.system.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.List;

/**
 * 自动加载数据源，项目启动后执行
 */
@Slf4j
@Component
public class AutoInitDataSourceJob {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private ISysDataSourceService sysDataSourceService;

    @Autowired
    private DruidDataSourceCreator druidDataSourceCreator;

    @PostConstruct
    public void execute() {
        try {
            List<SysDataSource> sysDataSourceList = sysDataSourceService.list();
            DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;

            for (SysDataSource sysDataSource : sysDataSourceList) {
                DataSourceProperty dataSourceProperty = new DataSourceProperty();
                dataSourceProperty.setPoolName(sysDataSource.getCode());
                dataSourceProperty.setDriverClassName(sysDataSource.getDbDriver());
                dataSourceProperty.setUrl(sysDataSource.getDbUrl());
                dataSourceProperty.setUsername(sysDataSource.getDbUsername());
                String decodedStr = SecurityUtil.jiemi(sysDataSource.getDbPassword());
                dataSourceProperty.setPassword(decodedStr);
                dataSourceProperty.setLazy(true);
                DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
                ds.addDataSource(sysDataSource.getCode(), dataSource);
            }

        }catch (Exception ex){
            log.error("AutoInitDataSourceJob 自动加载数据源异常 ",ex);
        }

    }
}
